package com.group4.Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.group4.DAO.UserDAO;
import com.group4.DB.User;
import com.group4.Utility.ActivationKeyGenerator;

@WebServlet( name="UpdateProfile", displayName="UpdateProfile", urlPatterns = {"/edit"})
public class UpdateProfile extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -378747896317887973L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
		String email = request.getParameter("email");
		UserDAO user = User.getUserWithUsername(username);
		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		if( user != null){
			user.setPassword(password);
			user.setEmail(email);
			User.updateUser(user);
			Gson gson = new Gson();
            String json = gson.toJson(user);
            out.print(json);
			out.flush();
		}
		else{
			
			jsonObject.addProperty("error", "there is no user with this username!");
			out.print(jsonObject);
			out.flush();
		}
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
		String email = request.getParameter("email");
		UserDAO user = User.getUserWithUsername(username);
		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		if( user != null){
			user.setPassword(password);
			user.setEmail(email);
			User.updateUser(user);
			Gson gson = new Gson();
            String json = gson.toJson(user);
            out.print(json);
			out.flush();
		}
		else{
			
			jsonObject.addProperty("error", "there is no user with this username!");
			out.print(jsonObject);
			out.flush();
		}
	}
}
